package org.steven.crm.core.service.salebill;

import com.steven.sequence.generater.SnowflakeGenerator;
import com.steven.xdb.dbmanager.DBManager;
import com.steven.xdb.pagination.query.AbstractQueryDataList;
import org.apache.commons.collections.CollectionUtils;
import org.steven.crm.core.service.BaseService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wuzw
 * @Date 2024/6/21 16:31
 * @Version 1.0
 */
public class SaleBillImageService extends BaseService {
    @Override
    protected String getTable() {
        return "saleBillImage";
    }

    @Override
    protected AbstractQueryDataList getQueryDataList() {
        return null;
    }

    @Override
    protected String getDataSourceName() {
        return null;
    }

    public void batchSave(String saleBillId, Collection<String> newImageFileIds) throws Exception {
        List<String> curImageFileIds = getSaleBillImageIds(saleBillId);

        Collection<String> keepImageFileIds = CollectionUtils.intersection(newImageFileIds, curImageFileIds);
        Collection<String> deleteImageFileIds = CollectionUtils.subtract(curImageFileIds, keepImageFileIds);
        Collection<String> addImageFileIds = CollectionUtils.subtract(newImageFileIds, keepImageFileIds);

        if (deleteImageFileIds.size() > 0) {
            String sql = "update " + getTable() + " set deleted = ? where saleBillId = ? and imageFileId in ("
                    + deleteImageFileIds.stream().collect(Collectors.joining(",")) + ")";
            List<String> p = new ArrayList<>();
            p.add(System.currentTimeMillis() + "");
            p.add(saleBillId);
            DBManager.update(getSession(), sql, p);
        }

        if (addImageFileIds.size() > 0) {
            List<Map<String, String>> addDatas = new ArrayList<>();
            for (String addImageFileId : addImageFileIds) {
                Map<String, String> addData = new HashMap<>();
                addData.put("id", SnowflakeGenerator.getIndex());
                addData.put("saleBillId", saleBillId);
                addData.put("imageFileId", addImageFileId);
                addDatas.add(addData);
            }
            DBManager.batchInsert(getSession(), getTable(), addDatas);
        }
    }

    public List<String> getSaleBillImageIds(String saleBillId) throws Exception {
        List<Map<String, String>> roles = getSaleBillImages(saleBillId);
        return roles.stream().map(e -> e.get("imageFileId")).collect(Collectors.toList());
    }

    public List<Map<String, String>> getSaleBillImages(String saleBillId) throws Exception {
        Map<String, String> k = new HashMap<>();
        k.put("saleBillId", saleBillId);
        k.put("deleted", "0");
        return DBManager.query(getSession(), getTable(), k);
    }
}
